package com.sptpc.demo.controller;

import com.sptpc.demo.model.Student;
import com.sptpc.demo.service.IStudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    public IStudentService studentService;

//    get AllStudent
//    查询所有学生
    @GetMapping("/")
    public List<Student> getAllStudent(){
        List<Student> allStudent = studentService.getAllStudents();
        return allStudent;
    }

//    新增学生信息
    @PostMapping("/add")
    public Student addNewStudent(@RequestBody @Valid Student student,
                                 BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            for (ObjectError error : bindingResult.getAllErrors()){
                log.error(error.toString());
            }
            return null;
        }else{
            log.info("新增的学生信息为，{}",student);
            studentService.addNewStudent(student);
            return student;
        }
    }

//    编辑学生信息
    @PutMapping("/update")
    public Student updateStudent(@RequestBody Student request){
        log.info("要修改的学生信息，{}",request);
//        查看有无此学生
        Student student = studentService.getStudentById(request.getId());
//        复制当前修改的属性
        BeanUtils.copyProperties(request,student);
//        更新数据库
        studentService.updateStudent(student);
        return student;
    }

//    删除学生
    @DeleteMapping("/{id}")
    public String deleteStudent(@PathVariable Long id){
        log.info("要删除的分类id：{}",id);
        studentService.deleteStudentById(id);
        return "删除成功";

    }
}
